package com.salim.leetcode.$92;

public class ReverseLinkedListII {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(head==null||left==right){
            return head;
        }
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode result = null;
        int index = 0;
        ListNode leftNode = dummy;
        dummy = dummy.next;
        left--;
        right--;
        while (dummy.next!=null && index<right){
            if(index>=left){
                ListNode leftNext = leftNode.next;
                leftNode.next = dummy.next;
                dummy.next = dummy.next.next;
                leftNode.next.next = leftNext;
                index++;
            }else{
                if(result==null){
                    result = leftNode.next;
                }
                leftNode = leftNode.next;
                dummy = dummy.next;
                index++;
            }
        }
        if(result==null){
            result = leftNode.next;
        }
        return result;
    }

    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
